﻿using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using Wicresoft.Logger;

namespace Wicresoft.Generic.Service
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            Environment.CurrentDirectory = new FileInfo(Assembly.GetEntryAssembly().Location).DirectoryName;
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            ServiceBase.Run(GlobalFactory.GetAllServices().ToArray());
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;

            try
            {
                if (ex != null)
                {
                    Log.Exception("System", ex);
                }
                else
                {
                    Log.Error("System", "Unknown error occurred, please contact system administrator (milesch@wicresoft.com) immediately!");
                }
            }
            catch (Exception ex2)
            {
                File.AppendAllText("system.log", String.Format("[{0}] {1}{2}", DateTime.Now, ex2.ToString(), Environment.NewLine));
            }
        }
    }
}
